/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: BaseService
 * Author:   wh
 * Date:     2019/4/19 15:56
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package io.imp.modules.tasks.unionqrc.service;

import io.imp.common.utils.AesEncryptUtils;
import io.imp.common.utils.DateUtils;
import io.imp.modules.sys.service.SysDictService;
import io.imp.modules.tasks.unionqrc.entity.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

import static io.imp.modules.tasks.unionqrc.task.ItcUnionqrcPackFile.*;

/**
 * @program: imp-security
 * @ClassName: BaseService
 * @Description:
 * @author: wanghui
 * @date: 2019/4/19 15:56
 * @Version: 1.0.0
 */
@Component
public class BaseService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    protected ItcsUnionpayTxnJnlService itcsUnionpayTxnJnlService;
    @Autowired
    protected ItcsStationInfoService itcsStationInfoService;
    @Autowired
    protected ItcsUnionpayCancelJnlService itcsUnionpayCancelJnlService;
    @Autowired
    protected ItcsUnionpayRefundJnlService itcsUnionpayRefundJnlService;
    @Autowired
    protected ItcsUnionpayReverseJnlService itcsUnionpayReverseJnlService;
    @Autowired
    protected ItcsTransOrderJnlService itcsTransOrderJnlService;
    @Autowired
    protected SysDictService sysDictService;
    @Autowired
    protected ItcsUnionpayTxnJnlPartService itcsUnionpayTxnJnlPartService;
    @Autowired
    protected ItcsTerminalInfoService itcsTerminalInfoService;

    public String getStringSource (ItcsUnionpayTxnJnl itcsUnionpayTxnJnl, ItcsTransOrderJnl itcstransOrderJnl,
                                   Map<String,String> stationMap, String terminalno, String estationid){


        if (terminalno == null || terminalno.equals("")){
            terminalno = "未找到终端号";
        }
        if (estationid == null || estationid.equals("")){
            estationid = "G0000000000000";
        }

        //获取站名
        String stationName = stationMap.get(estationid);
        //String stationName = itcsStationInfoService.getSnameBySid(estationid);
        //用来找撤销和退费的实体
        String queryId  = itcsUnionpayTxnJnl.getQueryid();
        logger.info("渠道订单的queryid{}",queryId);
        String qrNo = itcsUnionpayTxnJnl.getQrNo();
        logger.info("渠道订单的qrNo{}",qrNo);
        //解密后的qrNo
        String afterQrNo = null;
        try {
            afterQrNo = AesEncryptUtils.decrypt(qrNo,sysDictService.getDictValue("unionqrc","encryptKey"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //2 是交易成功
        StringBuilder result  = new StringBuilder();
        String txntype = itcsUnionpayTxnJnl.getTxntype();
        txntype = StringUtils.isBlank(txntype)?"01":txntype;
        String txnsubtype = itcsUnionpayTxnJnl.getTxnsubtype();
        txnsubtype = StringUtils.isBlank(txnsubtype)?"06":txnsubtype;
        result.append(itcsUnionpayTxnJnl.getMerid()).append("|").append(terminalno).append("|")
                .append(stationName).append("|").append(itcsUnionpayTxnJnl.getOrderid())
                .append("|").append(itcsUnionpayTxnJnl.getTxntime()).append("|").append(afterQrNo)
                .append("|").append(itcsUnionpayTxnJnl.getTxnamt()).append("|").append(txntype).append("|")
                .append(txnsubtype).append("|").append(itcsUnionpayTxnJnl.getTraceno()).append("|")
                .append(itcsUnionpayTxnJnl.getRespcode()).append("|").append(itcsUnionpayTxnJnl.getRespmsg())
                .append("|").append(itcsUnionpayTxnJnl.getSettledate()).append("|")
                .append(itcsUnionpayTxnJnl.getSettleamt()).append("|").append(itcsUnionpayTxnJnl.getAccno())
                .append("|").append("|").append("\r\n");
        if (itcsUnionpayTxnJnl.getTxnstate()!=null && itcsUnionpayTxnJnl.getTxnstate().equals("3")){
            // 3 是交易撤销
            ItcsUnionpayCancelJnl cancel= itcsUnionpayCancelJnlService.getByOrigqryid(queryId);
            if (cancel==null){
                result.append("为查找到相关撤销数据").append("\r\n");
            }else {
                txntype = cancel.getTxntype();
                txntype = StringUtils.isBlank(txntype)?"31":txntype;
                txnsubtype = cancel.getTxnsubtype();
                txnsubtype = StringUtils.isBlank(txnsubtype)?"00":txnsubtype;
                result.append(cancel.getMerid()).append("|").append(terminalno).append("|")
                        .append(stationName).append("|").append(cancel.getOrderid())
                        .append("|").append(cancel.getTxntime()).append("|")
                        .append("|").append(cancel.getTxnamt()).append("|").append(txntype).append("|")
                        .append(txnsubtype).append("|").append(cancel.getTraceno()).append("|")
                        .append(cancel.getRespcode()).append("|").append(cancel.getRespmsg())
                        .append("|").append(cancel.getSettledate()).append("|").append(cancel.getSettleamt())
                        .append("|").append(itcsUnionpayTxnJnl.getAccno()).append("|")
                        .append(itcsUnionpayTxnJnl.getOrderid()).append("|").append("消费撤销").append("\r\n");
            }
        } else if (itcsUnionpayTxnJnl.getTxnstate()!=null && itcsUnionpayTxnJnl.getTxnstate().equals("4")){
            //4 是交易退货
            ItcsUnionpayRefundJnl refund = itcsUnionpayRefundJnlService.getByOrigqryid(queryId);
            if (refund == null){
                result.append("为查找到相关退款数据").append("\r\n");
            }else {
                txntype = refund.getTxntype();
                txntype = StringUtils.isBlank(txntype)?"04":txntype;
                txnsubtype = refund.getTxnsubtype();
                txnsubtype = StringUtils.isBlank(txnsubtype)?"00":txnsubtype;
                result.append(refund.getMerid()).append("|").append(terminalno).append("|")
                        .append(stationName).append("|").append(refund.getOrderid())
                        .append("|").append(refund.getTxntime()).append("|")
                        .append("|").append(refund.getTxnamt()).append("|").append(txntype).append("|")
                        .append(txnsubtype).append("|").append(refund.getTraceno())
                        .append("|").append(refund.getRespcode()).append("|").append(refund.getRespmsg())
                        .append("|").append(refund.getSettledate()).append("|").append(refund.getSettleamt())
                        .append("|").append(itcsUnionpayTxnJnl.getAccno()).append("|")
                        .append(itcsUnionpayTxnJnl.getOrderid()).append("|").append("消费退货").append("\r\n");
            }
        }else if (itcsUnionpayTxnJnl.getTxnstate()!=null && itcsUnionpayTxnJnl.getTxnstate().equals("7")){
            //7 是交易冲正
            ItcsUnionpayReverseJnl reverse = itcsUnionpayReverseJnlService.getByOrigqryid(queryId);
            if (reverse == null){
                result.append("为查找到相关冲正数据").append("\r\n");
            }else {
                txntype = reverse.getTxntype();
                txntype = StringUtils.isBlank(txntype)?"99":txntype;
                txnsubtype = reverse.getTxnsubtype();
                txnsubtype = StringUtils.isBlank(txnsubtype)?"01":txnsubtype;

                result.append(reverse.getMerid()).append("|").append(terminalno).append("|")
                        .append(stationName).append("|").append(reverse.getOrderid())
                        .append("|").append(reverse.getTxntime()).append("|")
                        .append("|").append(reverse.getTxnamt()).append("|").append(txntype).append("|")
                        .append(txnsubtype).append("|").append("").append("|")
                        .append(reverse.getRespcode()).append("|").append(reverse.getRespmsg())
                        .append("|").append("").append("|").append("")
                        .append("|").append(itcsUnionpayTxnJnl.getAccno()).append("|")
                        .append(itcsUnionpayTxnJnl.getOrderid()).append("|").append("冲正").append("\r\n");
            }
        }

        return result.toString().replace("null","");
    }


    public String getStringSource(final HashMap<String,List> hashMap,final Map<String,ItcsTransOrderJnl> itcstransOrderJnlMap,
                                  final Map<String,String> stationMap){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        Calendar calendar = Calendar.getInstance();
        Date date = new  Date();
        calendar.setTime(date);

        StringBuilder result  = new StringBuilder();

        List<ItcsUnionpayTxnJnl> itcsUnionpayTxnJnls = hashMap.get(ItcsUnionpayTxnJnls);
        List<ItcsUnionpayCancelJnl> itcsUnionpayCancelJnls = hashMap.get(ItcsUnionpayCancelJnls);
        List<ItcsUnionpayRefundJnl> itcsUnionpayRefundJnls = hashMap.get(ItcsUnionpayRefundJnls);
        //渠道冲正
        List<ItcsUnionpayReverseJnl> itcsUnionpayReverseJnls = hashMap.get(ItcsUnionpayReverseJnls);

        final CountDownLatch latch = new CountDownLatch(4);
        //创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(4) ;
        WorkItcsUnionpayTxnJnl w1 = new WorkItcsUnionpayTxnJnl(
                itcsUnionpayTxnJnlService,itcsUnionpayTxnJnlPartService,itcsTransOrderJnlService,
                sysDictService,itcsUnionpayTxnJnls,latch,itcstransOrderJnlMap,stationMap,itcsTerminalInfoService);
        WorkItcsUnionpayCancelJnl w2 = new WorkItcsUnionpayCancelJnl(
                itcsUnionpayCancelJnlService,itcsUnionpayTxnJnlPartService,itcsUnionpayTxnJnlService,
                sysDictService,itcsUnionpayCancelJnls,latch);
        WorkItcsUnionpayRefundJnl w3 = new WorkItcsUnionpayRefundJnl(
                itcsUnionpayRefundJnlService,itcsUnionpayTxnJnlService,sysDictService,
                itcsUnionpayTxnJnlPartService,itcsUnionpayRefundJnls,latch);
        WorkItcsUnionpayReverseJnl w4 = new WorkItcsUnionpayReverseJnl(
                itcsUnionpayReverseJnlService,itcsUnionpayTxnJnlPartService,sysDictService,
                itcsUnionpayTxnJnlService,itcsUnionpayReverseJnls,latch);
        Future fw = pool.submit(w1);
        Future fw2 = pool.submit(w2);
        Future fw3 = pool.submit(w3);
        Future fw4 = pool.submit(w4);

        try {
            String sfw = fw.get().toString();
            String sfw2 = fw2.get().toString();
            String sfw3 = fw3.get().toString();
            String sfw4 = fw4.get().toString();
            result = result.append(sfw).append(sfw2).append(sfw3).append(sfw4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        finally {
            pool.shutdown();
        }

        return result.toString().replace("null","");
    }

    /**
     * 获得流水实体集合
     * @param createtime
     * @param nowTime
     * @param lTime
     * @return
     */
    public Map<String,ItcsTransOrderJnl> getItcstransOrderJnls(Date createtime, Date nowTime, Date lTime){
        Map<String,ItcsTransOrderJnl> result = new HashMap<String, ItcsTransOrderJnl>();
        List<ItcsTransOrderJnl> itcsTransOrderJnls = itcsTransOrderJnlService.getByCreatetime(createtime,nowTime,lTime);
        for (ItcsTransOrderJnl i:itcsTransOrderJnls) {
            ItcsTransOrderJnl itcsTransOrderJnl = new ItcsTransOrderJnl();
            itcsTransOrderJnl.setTerminalno(i.getTerminalno());
            itcsTransOrderJnl.setEstationid(i.getEstationid());
            result.put(i.getOrderno(),itcsTransOrderJnl);
        }
        return result;
    }

    /**
     * 获取所有站台名字
     * @return
     */
    public Map<String,String> getItcsStations(){
        Map<String,String> result = new HashMap<String, String>();
        List<ItcsStationInfo> itcsStationInfos = itcsStationInfoService.getItcsStationInfoBySid();
        for (ItcsStationInfo i:itcsStationInfos) {
            result.put(i.getStationid(),i.getName());
        }
        return result;
    }

    /**
     * 写文件的方法
     * @param path
     * @param prefix
     * @param suffix
     * @param resultList
     */
    public void writeFile (String path,String prefix,String suffix,List<String> resultList) {
        BufferedWriter bw = null;
        try {
            String relativePath = DateUtils.getToday("yyyyMMdd");
            File tranfileDir = new File(path, relativePath);
            if (!tranfileDir.exists()) {
                tranfileDir.mkdirs();
            }
            String fileName = prefix + DateUtils.getToday("yyyyMMddHHmmss") + suffix;
            File file = new File(tranfileDir,fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            bw = new BufferedWriter(fileWriter);
            for (String s : resultList) {
                bw.write(s);
            }
            logger.info("文件生成完成[{}]",file.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.flush();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
                e.getMessage();
            }
        }
    }
    /**
     * 写文件的方法
     * @param path
     * @param prefix
     * @param suffix
     * @param resultList
     */
    public void writeFile (String path,String relativePath,String prefix,String suffix,List<String> resultList) {
        BufferedWriter bw = null;
        try {
            File tranfileDir = new File(path, relativePath);
            if (!tranfileDir.exists()) {
                tranfileDir.mkdirs();
            }
            String fileName = prefix + DateUtils.getToday("yyyyMMddHHmmss") + suffix;
            File file = new File(tranfileDir,fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            bw = new BufferedWriter(fileWriter);
            for (String s : resultList) {
                bw.write(s);
            }
            logger.info("文件生成完成[{}]",file.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.flush();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
                e.getMessage();
            }
        }
    }
}
